package com.moxiao.yfjh.module.blind.controller.admin.member;

import com.moxiao.yfjh.framework.common.pojo.CommonResult;
import com.moxiao.yfjh.framework.common.pojo.PageResult;
import com.moxiao.yfjh.framework.excel.core.util.ExcelUtils;
import com.moxiao.yfjh.framework.ip.core.utils.AreaUtils;
import com.moxiao.yfjh.framework.operatelog.core.annotations.OperateLog;
import com.moxiao.yfjh.module.activity.service.ActivityInfoApiService;
import com.moxiao.yfjh.module.blind.common.TencentCloudImUtil;
import com.moxiao.yfjh.module.blind.controller.admin.member.vo.*;
import com.moxiao.yfjh.module.blind.controller.admin.memberusertag.vo.MemberUsertagExportReqVO;
import com.moxiao.yfjh.module.blind.convert.member.BlindMemberUserConvert;
import com.moxiao.yfjh.module.blind.convert.memberusertag.MemberUsertagConvert;
import com.moxiao.yfjh.module.blind.dal.dataobject.member.BlindMemberUserDO;
import com.moxiao.yfjh.module.blind.dal.dataobject.memberusertag.MemberUsertagDO;
import com.moxiao.yfjh.module.blind.service.member.BlindMemberUserService;
import com.moxiao.yfjh.module.blind.service.memberusertag.MemberUsertagService;
import com.moxiao.yfjh.module.system.api.user.AdminUserApi;
import com.moxiao.yfjh.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Random;

import static com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.moxiao.yfjh.framework.common.pojo.CommonResult.success;
import static com.moxiao.yfjh.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static com.moxiao.yfjh.framework.web.core.util.WebFrameworkUtils.getLoginUserId;
import static com.moxiao.yfjh.module.blind.enums.ErrorCodeConstants.MEMBER_USERTAG_DELETE_NOT_EXISTS;

@Tag(name = "管理后台 - 相亲会员用户")
@RestController
@RequestMapping("/blind/member-user")
@Validated
public class BlindMemberUserController {

    @Resource
    private BlindMemberUserService memberUserService;
    @Resource
    private TencentCloudImUtil tencentCloudImUtil;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private MemberUsertagService memberUsertagService;
    @Resource
    private ActivityInfoApiService activityInfoApiService;


    @PutMapping("/update")
    @Operation(summary = "更新相亲会员用户")
    @PreAuthorize("@ss.hasPermission('blind:member-user:update')")
    public CommonResult<Boolean> updateMemberUser(@Valid @RequestBody BlindMemberUserUpdateReqVO updateReqVO) {
        memberUserService.updateMemberUser(updateReqVO);
        if (CollectionUtils.isNotEmpty(updateReqVO.getMemberUserTagRespVOS())){
            memberUsertagService.updateMemberUserTagList(updateReqVO.getMemberUserTagRespVOS(),updateReqVO.getId());
        }
        return success(true);
    }

    @PutMapping("/auditAvatar")
    @Operation(summary = "审核头像")
    @PreAuthorize("@ss.hasPermission('blind:member-user:auditAvatar')")
    public CommonResult<Boolean> auditAvatar(@Valid @RequestBody BlindMemberUserUpdateReqVO updateReqVO) {
        Long loginUserId = getLoginUserId();
        BlindMemberUserDO memberUser = memberUserService.getMemberUser(updateReqVO.getId());
        if (Objects.nonNull(memberUser) && Objects.nonNull(updateReqVO.getAuditStatus())){
            updateReqVO.setAuitTime(LocalDateTime.now());
            AdminUserRespDTO user = adminUserApi.getUser(loginUserId);
            if(Objects.nonNull(user)){
                updateReqVO.setAuitUser(user.getNickname());
            }
            if (Objects.equals(updateReqVO.getAuditStatus(), (byte) 1) && Objects.nonNull(memberUser.getAuditAvatar())) {
                updateReqVO.setAvatar(updateReqVO.getAuditAvatar());
                tencentCloudImUtil.portraitSet(String.valueOf(updateReqVO.getId()), null, memberUser.getAuditAvatar());
            }else if (Objects.equals(updateReqVO.getAuditStatus(),(byte) 2)){
                if (Objects.equals(memberUser.getSex(),(byte) 1)){
                    updateReqVO.setAvatar("https://dev.moxiao.pro/profile/SC/default_boy_avatar.png");
                }else {
                    updateReqVO.setAvatar("https://dev.moxiao.pro/profile/SC/default_girl_avatar.png");
                }
            }
        }
        memberUserService.updateMemberUser(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除相亲会员用户")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('blind:member-user:delete')")
    public CommonResult<Boolean> deleteMemberUser(@RequestParam("id") Long id) {
        //活动数据验证
        if (activityInfoApiService.getMemberActivityInfo(id)) {
            throw exception(MEMBER_USERTAG_DELETE_NOT_EXISTS);
        }
        //报名
        if (activityInfoApiService.getMemberEnroll(id)) {
            throw exception(MEMBER_USERTAG_DELETE_NOT_EXISTS);
        }
        memberUserService.deleteMemberUser(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得相亲会员用户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('blind:member-user:query')")
    public CommonResult<BlindMemberUserRespVO> getMemberUser(@RequestParam("id") Long id) {
        BlindMemberUserDO memberUser = memberUserService.getMemberUser(id);
        BlindMemberUserRespVO blindMemberUserRespVO = BlindMemberUserConvert.INSTANCE.convert(memberUser);
        if (Objects.nonNull(blindMemberUserRespVO)){
            //籍贯 所在地 中文
            String areaId = blindMemberUserRespVO.getAreaId();
            if (Objects.nonNull(areaId) && StringUtils.isNotEmpty(areaId)){
                blindMemberUserRespVO.setAreaName(AreaUtils.getAreaName(areaId));
            }
            String nativePlace = blindMemberUserRespVO.getNativePlace();
            if (Objects.nonNull(nativePlace) && StringUtils.isNotEmpty(nativePlace)){
                blindMemberUserRespVO.setNativePlaceName(AreaUtils.getAreaName(nativePlace));
            }
            String matchWorkArea = blindMemberUserRespVO.getMatchWorkArea();
            if (Objects.nonNull(matchWorkArea) && StringUtils.isNotEmpty(matchWorkArea)){
                blindMemberUserRespVO.setMatchWorkAreaName(AreaUtils.getAreaName(matchWorkArea));
            }
            //用户标签
            MemberUsertagExportReqVO exportReqVO = new MemberUsertagExportReqVO();
            exportReqVO.setUserId(id);
            List<MemberUsertagDO> memberUsertagList = memberUsertagService.getMemberUsertagList(exportReqVO);
            blindMemberUserRespVO.setMemberUserTagRespVOS(MemberUsertagConvert.INSTANCE.convertList(memberUsertagList));
        }
        return success(blindMemberUserRespVO);
    }

    @GetMapping("/list")
    @Operation(summary = "获得相亲会员用户列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('blind:member-user:query')")
    public CommonResult<List<BlindMemberUserRespVO>> getMemberUserList(@RequestParam("ids") Collection<Long> ids) {
        List<BlindMemberUserDO> memberUserList = memberUserService.getMemberUserList(ids);
        return success(BlindMemberUserConvert.INSTANCE.convertList(memberUserList));
    }


    @GetMapping("/avatarReviewList")
    @Operation(summary = "获得相亲会员用户分页")
    @PreAuthorize("@ss.hasPermission('blind:member-user:avatar')")
    public CommonResult<PageResult<BlindMemberUserRespVO>> avatarReviewList(@Valid BlindMemberUserPageReqVO pageVO) {
        PageResult<BlindMemberUserDO> pageResult = memberUserService.avatarReviewList(pageVO);
        return success(BlindMemberUserConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/page")
    @Operation(summary = "获得相亲会员用户分页")
    @PreAuthorize("@ss.hasPermission('blind:member-user:query')")
    public CommonResult<PageResult<BlindMemberUserRespVO>> getMemberUserPage(@Valid BlindMemberUserPageReqVO pageVO) {
        PageResult<BlindMemberUserDO> pageResult = memberUserService.getMemberUserPage(pageVO);
        return success(BlindMemberUserConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出相亲会员用户 Excel")
    @PreAuthorize("@ss.hasPermission('blind:member-user:export')")
    @OperateLog(type = EXPORT)
    public void exportMemberUserExcel(@Valid BlindMemberUserExportReqVO exportReqVO,
                                      HttpServletResponse response) throws IOException {
        List<BlindMemberUserDO> list = memberUserService.getMemberUserList(exportReqVO);
        // 导出 Excel
        List<BlindMemberUserExcelVO> datas = BlindMemberUserConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "相亲会员用户.xls", "数据", BlindMemberUserExcelVO.class, datas);
    }

    /**
     * 分销员详情
     */
    @GetMapping("/getDistributionInfo")
    @Operation(summary = "获得分销员详情")
    @PreAuthorize("@ss.hasPermission('member:distribution:info')")
    public CommonResult<DistributionVo> getDistributionInfo(@RequestParam("id") Long id) {
        DistributionVo vo = memberUserService.getDistributionInfo(id);
        return success(vo);
    }
    /**
     * 分销员-订单列表
     */

    public static int generateRandomPageNumber(int totalItems, int itemsPerPage) {
        if (totalItems <= 0 || itemsPerPage <= 0) {
            throw new IllegalArgumentException("Total items and items per page must be positive integers.");
        }
        int totalPages = (int) Math.ceil((double) totalItems / itemsPerPage);
        Random random = new Random();
        int randomPage = random.nextInt(totalPages) + 1;
        return randomPage;
    }

    public static void main(String[] args) {
        int totalItems = 433; // 总数
        int itemsPerPage = 20; // 每页数量
        int randomPage = generateRandomPageNumber(totalItems, itemsPerPage);
        System.out.println("随机生成的页码为: " + randomPage);
    }
}
